package com.yesallchina.wxapp.officialaccount.config;

import com.yesallchina.wxapp.officialaccount.api.*;
import com.yesallchina.wxapp.officialaccount.context.SpringApplicationContext;
import com.yesallchina.wxapp.officialaccount.service.WxOfficialAccountInitializer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@EnableConfigurationProperties({
        WxOfficialAccountCommonProperties.class,
        WxOfficialAccountSpiProperties.class,
        WxOfficialAccountApiUrlProperties.class
})
@ConditionalOnClass(WxOfficialAccountInitializer.class)
@Configuration
public class WxOfficialAccountAutoConfig implements ApplicationContextAware {

    private ApplicationContext appCtx;

    @Autowired
    private WxOfficialAccountCommonProperties commonProp;
    @Autowired
    private WxOfficialAccountSpiProperties spiProp;
    @Autowired
    private WxOfficialAccountApiUrlProperties apiUrlProp;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appCtx = applicationContext;
    }

    @Bean
    public WxOfficialAccountInitializer init() {
        SpringApplicationContext springCtx = new SpringApplicationContext(appCtx);
        WxOfficialAccountInitializer initializer
                = new WxOfficialAccountInitializer(springCtx, commonProp, spiProp, apiUrlProp);
        return initializer;
    }

    @Bean
    public BasicSupportApi baseSupport(WxOfficialAccountInitializer initializer) {
        return new BasicSupportApi(initializer);
    }

    @Bean
    public UserManageApi userManage(BasicSupportApi basicSupport) {
        return new UserManageApi(basicSupport);
    }

    @Bean
    public WebPageBaseSupportApi webPageBaseSupport(BasicSupportApi basicSupport, UserManageApi userManage) {
        return new WebPageBaseSupportApi(basicSupport, userManage);
    }

    @Bean
    public AccountManageApi accountManage(BasicSupportApi basicSupport){
        return new AccountManageApi(basicSupport);
    }

    @Bean
    public MessageApi messageApi(BasicSupportApi basicSupport){
        return new MessageApi(basicSupport);
    }

    @Bean
    public IndexApi index(MessageApi messageApi,WebPageBaseSupportApi webPageBaseSupportApi){
        return new IndexApi(messageApi,webPageBaseSupportApi);
    }

    @Bean
    public UIMenuApi uiMenu(BasicSupportApi basicSupport){
        return new UIMenuApi(basicSupport);
    }

    @Bean
    public PayApi payApi(BasicSupportApi basicSupport){
        return new PayApi(basicSupport);
    }

}
